#!/usr/bin/env bash

# This script is used for setup k8s+calico all configurations in multi-nodes, one or more master(s)
#
# FileName     : dockerbuild.sh
# Path         : /app/ghxt/Dockerfile
# Author       : ymliu
# Create Date  : 2021-05-31 17:10
# WorkFlow     : To build docker image & export to ftp automatically.
#                mv -f /home/xtuser607/@delete/${1}.jar /app/ghxt/Dockerfile/
#                chown root:root ${1}.jar
#                docker build -f xx.dockerfile -t ghxt/xx:dev-today-$2
#                docker save xxx.image.tar
#                gzip ghxt/xxx.image.tar
#                cp ghxt/xxx.image.tar.gz /home/...
#                chown xtuser607 /home/...

# ----------------------------------------------------------------
function show_usage()
{
  echo "Usage: build docker image and push to ftp directory"
  echo ""
  echo "  dockerbuild.sh <module> <version>"
  echo ""
  echo "  <module>  : Such as ghxt-fi, sgcc, etc. Indicates ghxt-fi.jar, ghxt/ghxt-fi:dev-1114-123 ."
  echo "  <version> : As ending of tag for image."
  echo ""
  echo "For example: dockerbuild.sh ghxt-fi 110"
  echo "  As command upon, it will move ghxt-fi.jar, build image ghxt/ghxt-fi:dev-1114-110, mv file ghxt-fi_dev...image.tar.gz to ftp."
}

# ---- main ----
if [ $# -lt 2 ]; then
  show_usage
  exit 1
fi

declare -r MODULE=${1}
declare -r VERSION=${2}

pushd /app/ghxt/Dockerfile >/dev/null 2>&1

# mv jar
echo "mv ${MODULE}.jar..."
declare -r JAR=${MODULE}.jar
mv -f /home/xtuser607/@delete/${JAR} /app/ghxt/Dockerfile/
chown root:root /app/ghxt/Dockerfile/${JAR}

# docker build
echo "building docker image..."
declare -r DOCKERFILE="${MODULE}.dockerfile"
declare -r DATE=$(date +%m%d)
declare -r TAG=dev-${DATE}-${VERSION}
declare -r IMAGE=ghxt/${MODULE}:${TAG}
docker build -f ${DOCKERFILE} -t ${IMAGE} .

# docker save
echo "saving docker image ..."
declare -r TAR_FILE=${MODULE}_${TAG}.image.tar
docker save ${IMAGE} -o ghxt/${TAR_FILE}

# gzip
echo "gziping docker image..."
declare -r GZ_FILE=${TAR_FILE}.gz
gzip ghxt/${TAR_FILE}

# mv to ftp & chown
echo "mv tar.gz file to ftp..."
cp -f ghxt/${GZ_FILE} /home/xtuser607/@delete/
chown xtuser607 /home/xtuser607/@delete/${GZ_FILE}

popd >/dev/null 2>&1
